<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\api\controller\shop;

use app\api\controller\shop\Base;
use utils\Weixin\Jssdk;
use think\Session;
use think\Cookie;
use think\Cache;
use think\Config;
use think\Db;
//七牛
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
//
use utils\Weixin\WxPay;
use utils\Weixin\WxUser;
//
use think\captcha\Captcha;

error_reporting(E_ALL);

/**
 * @title 【公共类】
 */
class Everyone extends Base {

    public $userInfo;
    public $wxId;
    public $appid;
    public $appsecret;

    /**
     * @title 快速生成一条订单
     * @method post
     * @params address_detail 杭州市西湖区 黄龙万科中心
     * @params area_code 130302
     * @params city 秦皇岛市
     * @params county 海港区
     * @params is_default true
     * @params name 收货人
     * @params postal_code 100000
     * @params province 河北省
     * @params tel 18994094765
     * @params address_id 0 如果为0，则添加否则更新
     */
    public function quick_order() {

        $post = input('post.');

        $insert_id = db('order')->insertGetId([
            'shipping_province' => $post['province'],
            'shipping_city' => $post['city'],
            'shipping_county' => $post['county'],
            'shipping_address_detail' => $post['address_detail'],
            'shipping_name' => $post['name'],
            'shipping_tel' => $post['tel'],
            'remark' => $post['remark'],
            'create_time' => time(),
        ]);
        return ['code' => 0, 'msg' => 'success', 'data' => $insert_id];
    }

    /**
     * 封装base64位图片上传
     */
    public function _base64_upload($base64) {
        $base64_image = str_replace(' ', '+', $base64);
        // post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)) {
            //匹配成功
            if ($result[2] == 'jpeg') {
                $image_name = uniqid() . '.jpg';
                //纯粹是看jpeg不爽才替换的
            } else {
                $image_name = uniqid() . '.' . $result[2];
            }
            $image_file = ROOT_PATH . 'public' . DS . 'uploads' . DS . $image_name;
            // 服务器文件存储路径
            if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))) {
                return 'public' . DS . 'uploads' . DS . $image_name;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * @title 图片上传(BASE64)
     * @method post
     * @params file base64图片
     */
    public function imgupload() {

        $file = input('post.file', '');
        if (!empty($file)) {
            $result = $this->_base64_upload($file);

            if ($result) {
                return ['code' => 0, 'msg' => 'success', 'data' => $result];
            } else {
                return ['code' => 1, 'msg' => 'upload error'];
            }
        } else {
            return ['code' => 1, 'msg' => 'file empty'];
        }
    }

    /**
     * @title 图片上传(传统上传)
     * @method post
     * @params file
     */
    public function imgupload2() {

        $file = request()->file('file');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                // 成功上传后 获取上传信息
                // 输出 jpg
                echo $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                echo $info->getSaveName();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                echo $info->getFilename();
            } else {
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }

    /**
     * @title 留言反馈
     * @method post
     * @params content
     * @params contact
     */
    public function feedback() {

        $content = input('post.content', '');
        $contact = input('post.contact', '');
        $captchaCode = input('post.captcha', '');

        if (empty($content)) {
            return ['code' => 1, 'msg' => '内容不能为空'];
        }

        //
        $captcha = new Captcha();
        if (!$captcha->check($captchaCode)) {
            return ['code' => 1, 'msg' => '验证码输入有误'];
        }


        $affect_rows = db('feedback')->insert([
            'content' => $content,
            'contact' => $contact
        ]);

        return ['code' => 0, 'msg' => 'success', 'data' => $affect_rows];
    }

    /**
     * @title 微信支付回调
     */
    public function notify() {


        $xml = file_get_contents('php://input');

        $data = [];

        //file_put_contents(APP_DIR . '/weixin_callback00.txt', $xml, FILE_APPEND);
        // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        // 这句file_put_contents是用来查看服务器返回的XML数据 测试完可以删除了  
        //  file_put_contents(APP_DIR . '/weixin_callback.txt', $xml, FILE_APPEND);
        //将服务器返回的XML数据转化为数组  
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //$data = xmlToArray($xml);
        // 保存微信服务器返回的签名sign  
        $data_sign = $data['sign'];

        // sign不参与签名算法  
        unset($data['sign']);
        $sign = $this->_makeSign($data);

        // 判断签名是否正确  判断支付状态  
        if (($sign === $data_sign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS')) {
            $result = $data;



            //获取服务器返回的数据  
            $order_number = $data['out_trade_no'];  //订单单号  
            // $order_id = $data['attach'];        //附加参数,选择传递订单ID   
            $openid = $data['openid'];          //付款人openID  
            $total_fee = $data['total_fee'];    //付款金额 
            //这句file_put_contents是用来查看服务器返回的XML数据 测试完可以删除了  
            //file_put_contents(APP_DIR . '/weixin_callback2.txt',  $order_number . '+' . $openid . '+' . $total_fee, FILE_APPEND);



            /**
             * ----------------------------------------------业务----------------------------------------------------
             */
            //更新order状态
            db('order')->where('order_number', $order_number)->setField('status', 20);

            //更新order_history
            $order_id = db('order')->where('order_number', $order_number)->value('id');

            // 更新商品购买数量 
            $goods = db('order_goods')->where('order_id', $order_id)->field('goods_id,id')->select();
            foreach ($goods as $value) {
                db('goods')->where('id', $value['goods_id'])->setInc('sale_count');
            }


            //插入一条付款记录     
            db('order_history')->insert([
                'order_id' => $order_id,
                'order_status' => 20,
                'create_time' => time(),
                'remark' => '微信支付了' . ($total_fee / 100) . '元',
            ]);



            /**
             * ----------------------------------------------业务结束----------------------------------------------------
             */
        } else {
            $result = false;
        }
        // 返回状态给微信服务器  
        if ($result) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        //return $result;
    }

    /**
     * 微信支付回调-生成签名
     * 生成签名 
     * @return 签名，本函数不覆盖sign成员变量 
     */
    protected function _makeSign($data = []) {
        //获取微信支付秘钥  
        $wxpay = new WxPay();
        $key = $wxpay->pay_apikey;
        // 去空  
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数  
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY  
        //$config=$this->config;  
        $string_sign_temp = $string_a . "&key=" . $key;
        //签名步骤三：MD5加密  
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写  
        $result = strtoupper($sign);
        return $result;
    }

    /**
     * @title 用户登录（普通方式）
     * @method post
     * @params username admin 手机号
     * @params password 111111 密码
     */
    public function login() {



        $username = input('post.username', '');
        $password = input('post.password', '');


        if ($username && $password) {




            if (preg_match('/^\d{11}$/', $username)) {
                //手机号登录
                $where['mobile'] = $username;
            } elseif (preg_match('/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/', $username)) {
                //邮箱登录
                $where['email'] = $username;
            } else {
                //用户名登录
                $where['username'] = $username;
            }


            $result = db('member')
                    ->field('id,username,nickname,password,mobile,avatar')
                    ->where($where)
                    //  ->where('status', '>', 0)
                    ->find();


            if ($result) {

                // echo md5($password);

                if ($result['password'] != md5($password)) {
                    return ['code' => 1, 'msg' => '您输入的密码有误'];
                }

                //uid
                $uid = $result['id'];



                //更新登录次数
                $affect_rows = db('member')->where('id', $uid)->setInc('login_count');


                //写入一条登录信息
                //$log_data['user_id'] = $uid;
                //$log_data['action_ip'] = get_client_ip(1);
                //$log_data['remark'] = 'login';
                //db('action_log')->partition(['user_id' => $uid], "user_id", ['type' => 'mod', 'num' => 10])->insert($log_data);
                //保存一个随机值到redis中，以维持用户的登录状态 
                $uniqid = uniqid();

                //每登录一次，都会清空之前所有的值。
                Cache::set($uniqid, $uid, 3600 * 24 * 7);


                //返回用户信息
                return ['code' => 0, 'msg' => '登录成功', 'data' => $uniqid];
            } else {

                return ['code' => 1, 'msg' => '用户不存在或已禁用'];
            }
        } else {


            return ['code' => 1, 'msg' => '用户名或密码不能为空'];
        }
    }

    /**
     * @title 微信小程序登录
     * @method post
     * @params code
     * [userInfo] => Array
      (
      [nickName] => 色企鹅
      [gender] => 0
      [language] => zh_CN
      [city] =>
      [province] =>
      [country] =>
      [avatarUrl] => https://wx.qlogo.cn/mmopen/vi_32/VjsEU2iclDn0sGyKKUBFpRrqERj6Eicj3hrGz0mNWIL9l4GZh0u4iaSIuSiaqqf8DBiaQMmMcU3Eo6EnFoJJU5ENYIA/132
      )
     * Array
      (
      [session_key] => g1zBv71rI89mPRlFud+3mA==
      [openid] => omUJN5XZSUkkO5R4LguYO557Jp2U
      [unionid] => oqAEb001MhYD9yUfPkuhxo3_yjAQ
      )
     */
    public function wx_app_login() {

        $appid = config('wxapp.appid');
        $appsecret = config('wxapp.appsecret');


        $code = input('post.code');

        $userInfo = input('post.userInfo/a');


        if ($code) {

            $wxuser = new WxUser($appid, $appsecret);

            $sessionKey = $wxuser->sessionKey($code);

            if (!$sessionKey) {
                $error = $wxuser->getError();
                return ['code' => 1, 'msg' => $error];
            } else {

                // 获取到op和un值 后，保存数据库
                if (isset($sessionKey['openid']) && !empty($sessionKey['openid'])) {

                    //如果数据库存在，存cookies后直接登录
                    $user = db('member')->field('id,avatar,nickname,vip,openid,unionid')->where('unionid', $sessionKey['unionid'])->find();
                    if ($user) {

                        // 存在
                        // 审计
                        // 登录次数
                        db('member')->where('id', $user['id'])->setInc('login_count');

                        // 更新一下时间
                        db('member')->where('id', $user['id'])->setField('update_time', time());
                    } else {

                        // 新用户
                        //用户没有注册的情况下，马上注册为一个木马牛新用户
                        $data['unionid'] = $sessionKey['unionid'];
                        $data['openid'] = $sessionKey['openid'];

                        $data['avatar'] = $userInfo['avatarUrl'];

                        $data['nickname'] = $userInfo['nickName'];
                        $data['sex'] = $userInfo['gender'];

                        $data['country'] = $userInfo['country'];
                        $data['province'] = $userInfo['province'];
                        $data['city'] = $userInfo['city'];

                        $data['login_count'] = 0;
                        $data['create_time'] = time();
                        $data['update_time'] = time();

                        $user['id'] = db('member')->insertGetId($data);
                    }


                    $token = md5($sessionKey['unionid']);

                    // 保持鉴权值到redis
                    Cache::set($token, $user['id'], 3600 * 24 * 7); //有效期7天

                    return ['code' => 0, 'msg' => 'success', 'data' => $token];
                } else {
                    return ['code' => 1, 'msg' => 'openid empty'];
                }
            }
        } else {
            return ['code' => 1, 'msg' => 'code empty'];
        }
    }

    /**
     * @title 微信JSSDK分享签名
     * @method post
     * @params url 
     */
    public function wx_jssdk_sign() {

        $url = input('post.url');


        $appid = config('weixin.appid');
        $appsecret = config('weixin.appsecret');
        $jssdk = new Jssdk($appid, $appsecret);


        $sign = $jssdk->getSignPackage($url);

        return ['code' => 0, 'msg' => 'success', 'data' => $sign];
    }

    /**
     * @title 微信H5登录
     * @method get
     */
    public function wx_login() {



        // $event = controller('Weixin', 'event');


        $appid = config('weixin.appid');
        $appsecret = config('weixin.appsecret');


        $wxuser = new WxUser($appid, $appsecret);


        $userInfo = $wxuser->getWxUserInfo(APP_HOST . url('api/shop.everyone/wx_login'));



        //dd($userInfo);
        //
        //$access_token = $jssdk->getAccessToken();
        //print_r($openid_array);
        //Array ( 
        //[access_token] => 8_8-4B6h3d_VVsrbuD-a_zP2iNC7EdFJkwgxW1Jzp_ECO9F-vDLAKPhs4Ide9zoTmQ5y7LxJOwFTUx5cTy3xJWHw 
        //[expires_in] => 7200 
        //[refresh_token] => 8_JbInWtQLgRPoDZwBE3FdhjJYoDnIo-jfYx4dBB6rNVfIek29WxaCi67a5xnLaBEoA4v5VKDzP3UTYgR3fGMLwQ 
        //[openid] => oNehi0u8dgi6gZPtz-Osr6rnRKjs 
        //[scope] => snsapi_base )       

        /*
          Array
          (
          [subscribe] => 1
          [openid] => oNehi0u8dgi6gZPtz-Osr6rnRKjs
          [nickname] => 色企鹅
          [sex] => 1
          [language] => zh_CN
          [city] => 西城
          [province] => 北京
          [country] => 中国
          [headimgurl] => http://thirdwx.qlogo.cn/mmopen/LXqicVqwJiatr6JZibGc4K2bQv3pGQljic2aY314trvBe4EEbaAzicjEUXZsibdgFrobZUNE6iaVSKibCDORTeT9ltZjyQ/132
          [subscribe_time] => 1521606560
          [unionid] => oqAEb05uvc73P573o1wkY2S6abAo
          [remark] =>
          [groupid] => 0
          [tagid_list] => Array
          (
          )

          [subscribe_scene] => ADD_SCENE_SEARCH
          [qr_scene] => 0
          [qr_scene_str] =>
          )
         * 
          Array
          (
          [openid] => oNehi0u8dgi6gZPtz-Osr6rnRKjs
          [nickname] => 色企鹅
          [sex] => 1
          [language] => zh_CN
          [city] => West
          [province] => Beijing
          [country] => CN
          [headimgurl] => http://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEIe2AT9cJvWCK2ibrMoUfibHkuGNgmWvZicsib0wAfHrDtegic01jAbBAOzL9lzmLT4iaibicEbiaob76Xia9dg/132
          [privilege] => Array
          (
          )

          [unionid] => oqAEb05uvc73P573o1wkY2S6abAo
          )

         */


        //$this->login_check($userInfo);
        //  if (isset($userInfo['unionid']) && !empty($userInfo['unionid'])) {  //

        if (isset($userInfo['openid']) && !empty($userInfo['openid'])) {


            //如果数据库存在，存cookies后直接登录
            $user = db('member')->field('id,avatar,nickname,vip,openid,unionid')->where('unionid', $userInfo['unionid'])->find();

            if ($user) {

                //审计
                // 更新登录次数
                db('member')->where('id', $user['id'])->setInc('login_count');

                // 更新一下时间
                db('member')->where('id', $user['id'])->setField('update_time', time());
            } else {

                //用户没有注册的情况下，马上注册为一个木马牛新用户
                $data['unionid'] = $userInfo['unionid'];
                $data['openid'] = $userInfo['openid'];

                $data['avatar'] = $userInfo['headimgurl'];

                $data['nickname'] = $userInfo['nickname'];
                $data['sex'] = $userInfo['sex'];

                $data['country'] = $userInfo['country'];
                $data['province'] = $userInfo['province'];
                $data['city'] = $userInfo['city'];

                $data['login_count'] = 0;
                $data['create_time'] = time();
                $data['update_time'] = time();

                $user['id'] = db('member')->insertGetId($data);

                //$user = db('member')->field('id,avatar,nickname,vip,openid')->where('id', $insert_id)->find();
                // Session::set('user', $user->toArray());
            }


            $token = md5($userInfo['unionid']);

            // 保持鉴权值到redis
            Cache::set($token, $user['id'], 3600 * 24 * 7); //有效期7天


            $redirect_url = Config::get('weixin.redirect_uri');


            if ($redirect_url) {
                $this->redirect($redirect_url . '/h5/?#/login?token=' . $token);
            } else {
                exit('redirect url empty');
            }

            //exit($redirect_url . '/shop/?#/login?token=' . md5($user['unionid']));
            //  $this->redirect(url('weixin/setting/index'));
        } else {
            exit('unionid is null');
        }


        //print_r($userInfo);
    }

    /**
     * @title 微信用户注册 
     * 
     */
    public function _reg_tpos($userInfo) {






        /*
          if (isset($userInfo['headimgurl'])) {


          //把头像保存一份到七牛
          //$data['avatar'] = $userInfo['headimgurl'];
          //鉴权
          $bucket = config('qiniu.BUCKET_NAME');
          $accessKey = config('qiniu.ACCESS_KEY');
          $secretKey = config('qiniu.SECRET_KEY');

          $auth = new Auth($accessKey, $secretKey);

          // 生成上传Token
          $token = $auth->uploadToken($bucket);
          // 构建 UploadManager 对象
          $uploadMgr = new UploadManager();



          $filename_remote = APP_THEME . '/' . $insert_id . '/avatar/' . time() . '.jpg';

          //保存到服务器本地再上传
          $filename_local = APP_DIR . '/uploads/' . $insert_id . '.jpg';

          $this->_download($userInfo['headimgurl'], $filename_local);

          $ret = $uploadMgr->putFile($token, $filename_remote, $filename_local);

          $this->log($ret, 'wx');

          db('member')->where('id', $insert_id)->setField('avatar', $filename_remote);
          }

         */
        return $insert_id;
    }

}
